<template>
  <div class="question-bank">
    <h1>面试题库</h1>

    <div class="section">
      <h2>专业分类 
        <el-button type="success" size="small" circle @click="showAddCategoryDialog" title="添加分类">
          <el-icon><Plus /></el-icon>
        </el-button>
        <el-button type="danger" size="small" circle @click="deleteCurrentCategory" v-if="activeCategoryId" title="删除当前分类">
          <el-icon><Delete /></el-icon>
        </el-button>
      </h2>
      <div class="category-tabs">
        <el-button
          v-for="category in categories"
          :key="category.category_id"
          :type="activeCategoryId === category.category_id ? 'primary' : ''"
          @click="handleCategoryChange(category.category_id)"
        >
          {{ category.category_name }}
        </el-button>
      </div>
    </div>

    <div class="section">
      <h2>真题训练
        <el-button type="success" size="small" circle @click="showAddQuestionDialog" v-if="activeCategoryId" title="添加题目">
          <el-icon><Plus /></el-icon>
        </el-button>
      </h2>
      <div v-if="loading" class="loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载中...</span>
      </div>
      <div v-else-if="questions.length === 0" class="no-data">暂无题目数据</div>
      <div v-else class="question-list">
        <el-card class="question-card" v-for="question in questions" :key="question.question_id" shadow="hover">
          <h3>{{ question.question_content }}</h3>
          <div class="actions">
            <el-button 
              :type="expandedQuestions.includes(question.question_id) ? 'primary' : 'default'"
              size="small"
              @click="toggleAnswer(question.question_id)"
            >
              {{ expandedQuestions.includes(question.question_id) ? '收起解析' : '查看解析' }}
            </el-button>
            <el-button type="warning" size="small" @click="showEditQuestionDialog(question)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button type="danger" size="small" @click="deleteQuestion(question.question_id)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </div>
          <!-- 答案显示区域 -->
          <el-collapse-transition>
            <div v-if="expandedQuestions.includes(question.question_id)" class="answer-section">
              <div v-if="question.answers && question.answers.length > 0" class="answer-content">
                <h4>解析：</h4>
                <div v-for="answer in question.answers" :key="answer.answer_id" class="answer-item">
                  <p>{{ answer.answer_content }}</p>
                </div>
              </div>
              <div v-else class="no-answer">
                <p>暂无解析内容</p>
          </div>
        </div>
          </el-collapse-transition>
        </el-card>
      </div>
    </div>

    <el-pagination
      v-if="pagination.pages > 1"
      class="pagination"
      :current-page="pagination.current"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      layout="prev, pager, next, total"
      @current-change="handlePageChange"
    />

    <!-- 添加/编辑分类对话框 -->
    <el-dialog 
      v-model="categoryDialogVisible" 
      :title="categoryForm.category_id ? '编辑分类' : '添加分类'"
      width="500px"
    >
      <el-form :model="categoryForm" label-width="100px">
        <el-form-item label="分类名称">
          <el-input v-model="categoryForm.category_name" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑题目对话框 -->
    <el-dialog 
      v-model="questionDialogVisible" 
      :title="questionForm.question_id ? '编辑题目' : '添加题目'"
      width="600px"
    >
      <el-form :model="questionForm" label-width="100px">
        <el-form-item label="题目内容">
          <el-input 
            v-model="questionForm.question_content" 
            type="textarea" 
            :rows="4"
            placeholder="请输入题目内容" 
          />
        </el-form-item>
        <el-form-item label="答案解析">
          <el-input 
            v-model="questionForm.answer_content" 
            type="textarea" 
            :rows="6"
            placeholder="请输入答案解析（可选）" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="questionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveQuestion">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Edit, Loading } from '@element-plus/icons-vue'

const categories = ref([])
const activeCategoryId = ref(null)
const questions = ref([])
const loading = ref(false)
const expandedQuestions = ref([])
const pagination = ref({
  current: 1,
  pageSize: 5,
  total: 0,
  pages: 0
})

// 对话框控制
const categoryDialogVisible = ref(false)
const questionDialogVisible = ref(false)

// 表单数据
const categoryForm = ref({
  category_id: null,
  category_name: ''
})

const questionForm = ref({
  question_id: null,
  category_id: null,
  question_content: '',
  answer_content: '',
  answer_id: null
})

// 加载题目列表
const loadQuestions = async (categoryId, page = 1) => {
  loading.value = true
  try {
    const params = new URLSearchParams({
      page: page.toString(),
      pageSize: '5'
    })
    if (categoryId) {
      params.append('category_id', categoryId.toString())
    }

    const url = `/api/question?${params.toString()}`
    const res = await fetch(url)
    const json = await res.json()

    if (json && json.code === 200 && Array.isArray(json.data)) {
      questions.value = json.data
      if (json.pagination) {
        pagination.value = json.pagination
      }
      expandedQuestions.value = []
    } else {
      questions.value = []
      pagination.value = {
        current: 1,
        pageSize: 5,
        total: 0,
        pages: 0
      }
    }
  } catch (e) {
    console.error('获取题目列表失败:', e)
    ElMessage.error('获取题目列表失败')
    questions.value = []
  } finally {
    loading.value = false
  }
}

// 切换答案显示
const toggleAnswer = (questionId) => {
  const index = expandedQuestions.value.indexOf(questionId)
  if (index > -1) {
    expandedQuestions.value.splice(index, 1)
  } else {
    expandedQuestions.value.push(questionId)
  }
}

// 分页处理
const handlePageChange = (page) => {
  pagination.value.current = page
  loadQuestions(activeCategoryId.value, page)
}

// 切换分类
const handleCategoryChange = (categoryId) => {
  activeCategoryId.value = categoryId
}

// 显示添加分类对话框
const showAddCategoryDialog = () => {
  categoryForm.value = {
    category_id: null,
    category_name: ''
  }
  categoryDialogVisible.value = true
}

// 保存分类
const saveCategory = async () => {
  if (!categoryForm.value.category_name || !categoryForm.value.category_name.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }

  try {
    const url = categoryForm.value.category_id 
      ? `/api/question-category/${categoryForm.value.category_id}`
      : '/api/question-category'
    
    const method = categoryForm.value.category_id ? 'PUT' : 'POST'
    
    const res = await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ category_name: categoryForm.value.category_name.trim() })
    })
    
    const json = await res.json()
    if (json && (json.code === 200 || json.code === 201)) {
      ElMessage.success(categoryForm.value.category_id ? '更新成功' : '添加成功')
      categoryDialogVisible.value = false
      location.reload()
    } else {
      ElMessage.error(json.message || '操作失败')
    }
  } catch (e) {
    console.error('保存分类失败:', e)
    ElMessage.error('操作失败')
  }
}

// 删除当前分类
const deleteCurrentCategory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定删除此分类？分类下的所有题目也将被删除！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const res = await fetch(`/api/question-category/${activeCategoryId.value}`, { 
      method: 'DELETE' 
    })
    const json = await res.json()
    if (json && json.code === 200) {
      ElMessage.success('删除成功')
      location.reload()
    } else {
      ElMessage.error(json.message || '删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('删除失败:', e)
      ElMessage.error('删除失败')
    }
  }
}

// 显示添加题目对话框
const showAddQuestionDialog = () => {
  questionForm.value = {
    question_id: null,
    category_id: activeCategoryId.value,
    question_content: '',
    answer_content: '',
    answer_id: null
  }
  questionDialogVisible.value = true
}

// 显示编辑题目对话框
const showEditQuestionDialog = (question) => {
  questionForm.value = {
    question_id: question.question_id,
    category_id: question.category_id,
    question_content: question.question_content,
    answer_content: question.answers?.[0]?.answer_content || '',
    answer_id: question.answers?.[0]?.answer_id || null
  }
  questionDialogVisible.value = true
}

// 保存题目
const saveQuestion = async () => {
  if (!questionForm.value.question_content || !questionForm.value.question_content.trim()) {
    ElMessage.warning('请输入题目内容')
    return
  }

  try {
    // 保存题目
    const questionUrl = questionForm.value.question_id 
      ? `/api/question/${questionForm.value.question_id}`
      : '/api/question'
    
    const questionMethod = questionForm.value.question_id ? 'PUT' : 'POST'
    
    const questionData = {
      question_content: questionForm.value.question_content.trim()
    }
    if (!questionForm.value.question_id) {
      questionData.category_id = questionForm.value.category_id
    }
    
    const res = await fetch(questionUrl, {
      method: questionMethod,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(questionData)
    })
    
    const json = await res.json()
    if (json && (json.code === 200 || json.code === 201)) {
      const questionId = questionForm.value.question_id || json.data.question_id
      
      // 处理答案
      const answerContent = questionForm.value.answer_content?.trim()
      const answerId = questionForm.value.answer_id
      
      if (answerContent) {
        // 添加或更新答案
        if (answerId) {
          await fetch(`/api/question-answer/${answerId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ answer_content: answerContent })
          })
        } else {
          await fetch('/api/question-answer', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              question_id: questionId,
              answer_content: answerContent
            })
          })
        }
      } else if (answerId) {
        // 删除答案（如果答案被清空）
        await fetch(`/api/question-answer/${answerId}`, {
          method: 'DELETE'
        })
      }
      
      ElMessage.success(questionForm.value.question_id ? '更新成功' : '添加成功')
      questionDialogVisible.value = false
      await loadQuestions(activeCategoryId.value, pagination.value.current)
    } else {
      ElMessage.error(json.message || '操作失败')
    }
  } catch (e) {
    console.error('保存题目失败:', e)
    ElMessage.error('操作失败')
  }
}

// 删除题目
const deleteQuestion = async (questionId) => {
  try {
    await ElMessageBox.confirm(
      '确定删除此题目？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const res = await fetch(`/api/question/${questionId}`, { method: 'DELETE' })
    const json = await res.json()
    if (json && json.code === 200) {
      ElMessage.success('删除成功')
      await loadQuestions(activeCategoryId.value, pagination.value.current)
    } else {
      ElMessage.error(json.message || '删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('删除失败:', e)
      ElMessage.error('删除失败')
    }
  }
}

onMounted(async () => {
  try {
    const res = await fetch('/api/question-category')
    const json = await res.json()
    if (json && json.code === 200 && Array.isArray(json.data)) {
      categories.value = json.data
      if (json.data.length > 0) {
        activeCategoryId.value = json.data[0].category_id
        await loadQuestions(json.data[0].category_id)
      }
    }
  } catch (e) {
    console.error('初始化失败:', e)
    ElMessage.error('初始化失败')
  }
})

watch(activeCategoryId, (newCategoryId) => {
  if (newCategoryId) {
    pagination.value.current = 1
    loadQuestions(newCategoryId, 1)
  }
})
</script>

<style scoped>
.question-bank {
  width: 100%;
}

h1 {
  margin: 0 0 30px 0;
  color: #333;
}

.section {
  background: white;
  padding: 25px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.section h2 {
  margin: 0 0 20px 0;
  color: #333;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.category-tabs {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.question-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.question-card {
  border-radius: 8px;
}

.question-card h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
}

.actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.answer-section {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.answer-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.answer-content p {
  margin: 0;
  color: #555;
  line-height: 1.6;
  white-space: pre-wrap;
}

.no-answer {
  color: #999;
  font-style: italic;
}

.no-answer p {
  margin: 0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.is-loading {
  font-size: 20px;
}
</style>
